package cn.homework.egweibo2.controller;

import cn.homework.egweibo2.pojo.dto.UserDTO;
import cn.homework.egweibo2.pojo.entity.User;
import cn.homework.egweibo2.pojo.mapper.UserMapper;
import cn.homework.egweibo2.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    // 自动装配
    @Autowired
    private UserMapper userMapper;

    // 模拟注册
    @PostMapping("register")
    @ApiOperation(value = "用户注册")
    public int register(@RequestBody UserDTO userDTO) {

        log.debug("用户注册"+userDTO);
        // 获取用户电话
        String phone = userDTO.getPhone();

        // 查询接口 判断用户是否存在
        UserVO userVO = userMapper.selectByPhone(phone);
        if(userVO != null){
            return 2;
        }

        // 调用插入接口
        try{
            User user = new User();
            BeanUtils.copyProperties(userDTO, user);
            user.setCreated(new Date());
            userMapper.insert(user);
            return 1;
        }catch (Exception e){
            log.error("插入失败" + e.getMessage());
            return 0;
        }

    }

    @GetMapping("select")
    @ApiOperation(value = "查询用户信息")
    @ApiImplicitParam(name = "phone", value = "用户电话", required = true)
    public UserVO select(String phone){

        UserVO userVO = userMapper.selectByPhone(phone);
        log.debug("查询用户信息");

        return userVO;
    }

}
